package org.example.utils;

import com.alibaba.fastjson.JSON;
import org.example.exceptions.BusinessException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static org.example.enums.ErrorCodeEnum.PARAMS_EXCEPTION;


public class ValidateUtils {
    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    public static <T> Map<String, String> validate(T obj, Class<?>... var2) {
        Map<String, StringBuilder> errorMap = new HashMap();
        Set<ConstraintViolation<T>> set = validator.validate(obj, var2);
        if (set != null && set.size() > 0) {
            String property = null;
            Iterator var5 = set.iterator();

            while(var5.hasNext()) {
                ConstraintViolation<T> cv = (ConstraintViolation)var5.next();
                property = cv.getPropertyPath().toString();
                if (errorMap.get(property) != null) {
                    ((StringBuilder)errorMap.get(property)).append("," + cv.getMessage());
                } else {
                    StringBuilder sb = new StringBuilder();
                    sb.append(cv.getMessage());
                    errorMap.put(property, sb);
                }
            }
        }

        return errorMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey
        , (v) -> v.getValue().toString()
        ));
    }

    public static <T> void validateObj(T obj, Class<?>... var2) {
        Map<String, String> map = validate(obj, var2);
        if (!map.isEmpty()) {
            throw new BusinessException(PARAMS_EXCEPTION.getCode(), "校验异常:" + JSON.toJSONString(map));
        }
    }
}
